(:
  A procedure to detect patterns in a display file
:)

import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;

declare boundary-space strip;
declare variable $file := $arguments[1];
declare variable $facetnames := $arguments[2];
declare variable $sequence := $arguments[3];
declare variable $window := xs:integer($arguments[4]);
declare variable $seqlen := fn:count(fn:tokenize($sequence,">"));

declare function local:calculate-sequences ($context as item()*, $number as xs:integer, $current as element()) as item()* 
		{
			if ($number = 0) then $current (: stop recursion :)
			else if (fn:empty($context)) then () (: not enough to grant complete sequence :)
			else
				for $item at $pos in $context 
				let $newcurrent := <list>{
					($current/item,
					<item>{xs:string(jj:get-info($item,$facetnames))}</item>)}</list>
				return
					local:calculate-sequences($context[fn:position() > $pos], $number - 1, $newcurrent)
		};

<display>{
let $items := doc($file)/display/item


for $item at $pos in $items
	let $init := <list><item>{xs:string(jj:get-info($item,$facetnames))}</item></list>
	let $seqs := local:calculate-sequences($items[fn:position() = ($pos+1 to $pos+$window - 1)],$seqlen - 1,$init)
	let $prettyseqs := for $seq in $seqs 
	      let $stringseq := for $v in $seq/item return xs:string($v)
	      return string-join($stringseq, ' > ')
	where $prettyseqs = $sequence
	return $items[fn:position() = ($pos to $pos+$window - 1)]
 
}</display>
